import React, { useState, useEffect } from 'react';
import apiClient from '../../utils/apiClient';
    import './index.css';

    const HomePage = () => {
      const [knowledgeBases, setKnowledgeBases] = useState([]);
      const [searchTerm, setSearchTerm] = useState('');

      useEffect(() => {
        apiClient.get('/knowledge-bases').then(response => {
          setKnowledgeBases(response.data);
        }).catch(error => {
          console.error('Failed to fetch knowledge bases:', error);
        });
      }, []);

      const filteredKbs = knowledgeBases.filter(kb => 
        kb.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        kb.description.toLowerCase().includes(searchTerm.toLowerCase())
      );

      const handleCreateNew = () => {
        window.location.hash = '#/create-kb';
      };

      return (
        <div className="container home-page">
          <div className="page-header">
            <h1><i className="fas fa-database"></i> 知识库列表</h1>
            <button onClick={handleCreateNew}><i className="fas fa-plus"></i> 创建新知识库</button>
          </div>
          
          <input 
            type="search" 
            placeholder="搜索知识库..." 
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />

          {filteredKbs.length > 0 ? (
            <div className="kb-grid">
              {filteredKbs.map(kb => (
                <div key={kb.id} className="kb-card">
                  <div className="kb-card-header">
                    <i className="fas fa-book kb-icon"></i>
                    <h3>
                      <a href={`#/kb/${kb.id}?name=${encodeURIComponent(kb.name)}`}>{kb.name}</a>
                    </h3>
                  </div>
                  <p className="kb-description">{kb.description}</p>
                  <div className="kb-meta">
                    <span><i className="fas fa-file-alt"></i> {kb.docCount} 篇文档</span>
                    <span><i className="fas fa-clock"></i> 更新于: {kb.lastUpdated}</span>
                  </div>
                  <div className="kb-actions">
                    <a href={`#/kb/${kb.id}?name=${encodeURIComponent(kb.name)}`} className="action-btn view-btn">
                      <i className="fas fa-eye"></i> 查看
                    </a>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="empty-state">没有找到匹配的知识库。 <a href="#/create-kb">创建一个新的？</a></p>
          )}
        </div>
      );
    };

    export default HomePage;
